import React, { useState } from 'react'
import { clearHistory, exportHistory, deleteHistoryRecord } from '../utils/storage'

const HistoryPanel = ({ history, onSelectHistory, onHistoryUpdate, onOpenBackgroundPreview }) => {
  const [isOpen, setIsOpen] = useState(false)
  const [showConfirmClear, setShowConfirmClear] = useState(false)

  const handleDeleteRecord = (recordId, event) => {
    event.stopPropagation() // 防止触发选择历史记录
    if (deleteHistoryRecord(recordId)) {
      const updatedHistory = history.filter(record => record.id !== recordId)
      onHistoryUpdate(updatedHistory)
    }
  }

  const handleClearHistory = () => {
    if (clearHistory()) {
      onHistoryUpdate([])
      setShowConfirmClear(false)
    }
  }

  const handleExportHistory = () => {
    exportHistory()
  }

  const formatDate = (timestamp) => {
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  const truncateText = (text, maxLength = 20) => {
    if (!text || typeof text !== 'string') {
      return '无内容'
    }
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
  }

  if (!isOpen) {
    return (
      <button
        onClick={() => setIsOpen(true)}
        className="fixed top-4 right-4 z-20 bg-paper-100 hover:bg-paper-200 border border-ink-200 rounded-lg px-4 py-2 shadow-lg transition-all duration-200"
      >
        <span className="text-ink-600 text-sm">📜 历史记录 ({history?.length || 0})</span>
      </button>
    )
  }

  return (
    <div className="fixed top-0 right-0 h-full w-80 bg-paper-50 border-l border-ink-200 shadow-xl z-20 overflow-hidden">
      {/* 头部 */}
      <div className="bg-paper-100 border-b border-ink-200 p-4">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold text-ink-700 font-chinese">历史记录</h3>
          <button
            onClick={() => setIsOpen(false)}
            className="text-ink-500 hover:text-ink-700 text-xl"
          >
            ✕
          </button>
        </div>
        
        {/* 操作按钮 */}
        <div className="flex space-x-2 mt-3">
          <button
            onClick={handleExportHistory}
            className="flex-1 bg-gold-100 hover:bg-gold-200 text-gold-700 px-3 py-1 rounded text-sm transition-colors"
          >
            📤 导出
          </button>
          <button
            onClick={() => setShowConfirmClear(true)}
            className="flex-1 bg-ink-100 hover:bg-ink-200 text-ink-600 px-3 py-1 rounded text-sm transition-colors"
          >
            🗑️ 清空
          </button>
        </div>
      </div>

      {/* 历史记录列表 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-3">
        {!history || history.length === 0 ? (
          <div className="text-center text-ink-400 py-8">
            <p>暂无历史记录</p>
            <p className="text-sm mt-2">开始您的第一次心语对话吧</p>
          </div>
        ) : (
          history.map((record) => (
            <div
              key={record.id}
              onClick={() => onSelectHistory(record)}
              className={`bg-paper-100 border border-ink-200 rounded-lg p-3 cursor-pointer hover:bg-paper-200 transition-colors relative group ${
                record.isError ? 'border-red-200 bg-red-50' : ''
              }`}
            >
              {/* 操作按钮组 */}
              <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex space-x-1">
                {/* 预览按钮 */}
                {record.generatedImage?.success && onOpenBackgroundPreview && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      onOpenBackgroundPreview(record.id)
                    }}
                    className="bg-blue-100 hover:bg-blue-200 text-blue-600 rounded-full w-6 h-6 flex items-center justify-center text-xs"
                    title="预览背景"
                  >
                    👁
                  </button>
                )}

                {/* 删除按钮 */}
                <button
                  onClick={(e) => handleDeleteRecord(record.id, e)}
                  className="bg-red-100 hover:bg-red-200 text-red-600 rounded-full w-6 h-6 flex items-center justify-center text-xs"
                  title="删除这条记录"
                >
                  ✕
                </button>
              </div>

              <div className="text-xs text-ink-400 mb-2">
                {formatDate(record.timestamp)}
              </div>

              <div className="text-sm text-ink-600 mb-2 pr-8">
                <span className="font-medium">心语：</span>
                {truncateText(record.userInput)}
              </div>

              <div className="text-xs text-ink-500">
                <span className="font-medium">情绪：</span>
                {record.aiResponse?.emotion || '未知'}
              </div>

              {record.isError && (
                <div className="text-xs text-red-500 mt-1">
                  ⚠️ 生成失败
                </div>
              )}
            </div>
          ))
        )}
      </div>

      {/* 确认清空对话框 */}
      {showConfirmClear && (
        <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
          <div className="bg-paper-50 rounded-lg p-6 m-4 max-w-sm">
            <h4 className="text-lg font-semibold text-ink-700 mb-3">确认清空</h4>
            <p className="text-ink-600 mb-4">确定要清空所有历史记录吗？此操作不可撤销。</p>
            <div className="flex space-x-3">
              <button
                onClick={() => setShowConfirmClear(false)}
                className="flex-1 bg-ink-100 hover:bg-ink-200 text-ink-600 py-2 rounded transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleClearHistory}
                className="flex-1 bg-red-500 hover:bg-red-600 text-white py-2 rounded transition-colors"
              >
                确认清空
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default HistoryPanel
